package com.ruoyi.pack.service.impl;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.constant.UserConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.pack.mapper.PackWarehouseMapper;
import com.ruoyi.pack.domain.PackWarehouse;
import com.ruoyi.pack.domain.PackWarehouseFence;
import com.ruoyi.pack.service.IPackWarehouseService;
import com.ruoyi.pack.service.IPackWarehouseFenceService;
import com.ruoyi.pack.domain.dto.FenceInfoDto;
import com.ruoyi.pack.domain.dto.FenceOperationDto;
import com.ruoyi.pack.domain.dto.FenceOperationResultDto;
import com.ruoyi.pack.domain.dto.FencePointDto;
import com.ruoyi.common.exception.ServiceException;

/**
 * 仓库Service业务层处理
 * 
 * @author ruoyi
 */
@Service
public class PackWarehouseServiceImpl implements IPackWarehouseService 
{
    @Autowired
    private PackWarehouseMapper packWarehouseMapper;

    @Autowired
    private IPackWarehouseFenceService packWarehouseFenceService;

    /**
     * 查询仓库
     * 
     * @param warehouseId 仓库主键
     * @return 仓库
     */
    @Override
    public PackWarehouse selectPackWarehouseByWarehouseId(Long warehouseId)
    {
        return packWarehouseMapper.selectPackWarehouseByWarehouseId(warehouseId);
    }

    /**
     * 查询仓库列表
     * 
     * @param packWarehouse 仓库
     * @return 仓库
     */
    @Override
    public List<PackWarehouse> selectPackWarehouseList(PackWarehouse packWarehouse)
    {
        return packWarehouseMapper.selectPackWarehouseList(packWarehouse);
    }

    /**
     * 查询仓库列表（用于导出，包含关联名称信息）
     * 
     * @param packWarehouse 仓库
     * @return 仓库
     */
    @Override
    public List<PackWarehouse> selectPackWarehouseListForExport(PackWarehouse packWarehouse)
    {
        return packWarehouseMapper.selectPackWarehouseListForExport(packWarehouse);
    }

    /**
     * 新增仓库
     * 
     * @param packWarehouse 仓库
     * @return 结果
     */
    @Override
    public int insertPackWarehouse(PackWarehouse packWarehouse)
    {
        packWarehouse.setCreateTime(DateUtils.getNowDate());
        return packWarehouseMapper.insertPackWarehouse(packWarehouse);
    }

    /**
     * 修改仓库
     * 
     * @param packWarehouse 仓库
     * @return 结果
     */
    @Override
    public int updatePackWarehouse(PackWarehouse packWarehouse)
    {
        packWarehouse.setUpdateTime(DateUtils.getNowDate());
        return packWarehouseMapper.updatePackWarehouse(packWarehouse);
    }

    /**
     * 批量删除仓库
     * 
     * @param warehouseIds 需要删除的仓库主键
     * @return 结果
     */
    @Override
    public int deletePackWarehouseByWarehouseIds(Long[] warehouseIds)
    {
        return packWarehouseMapper.deletePackWarehouseByWarehouseIds(warehouseIds);
    }

    /**
     * 删除仓库信息
     * 
     * @param warehouseId 仓库主键
     * @return 结果
     */
    @Override
    public int deletePackWarehouseByWarehouseId(Long warehouseId)
    {
        return packWarehouseMapper.deletePackWarehouseByWarehouseId(warehouseId);
    }

    /**
     * 校验仓库编码是否唯一
     * 
     * @param packWarehouse 仓库信息
     * @return 结果
     */
    @Override
    public boolean checkWarehouseCodeUnique(PackWarehouse packWarehouse)
    {
        Long warehouseId = StringUtils.isNull(packWarehouse.getWarehouseId()) ? -1L : packWarehouse.getWarehouseId();
        PackWarehouse info = packWarehouseMapper.checkWarehouseCodeUnique(packWarehouse.getWarehouseCode());
        if (StringUtils.isNotNull(info) && info.getWarehouseId().longValue() != warehouseId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增仓库（包含围栏信息）
     * 
     * @param packWarehouse 仓库
     * @return 结果信息，包含创建的围栏ID列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> insertPackWarehouseWithFence(PackWarehouse packWarehouse)
    {
        Map<String, Object> result = new HashMap<>();
        List<Long> fenceIds = new ArrayList<>();
        
        // 1. 创建仓库
        packWarehouse.setCreateTime(DateUtils.getNowDate());
        int warehouseResult = packWarehouseMapper.insertPackWarehouse(packWarehouse);
        
        if (warehouseResult > 0 && packWarehouse.getFenceList() != null && !packWarehouse.getFenceList().isEmpty())
        {
            // 2. 创建围栏
            for (FenceInfoDto fenceInfo : packWarehouse.getFenceList())
            {
                if (fenceInfo.getPoints() != null && fenceInfo.getPoints().size() >= 3)
                {
                    // 为每个围栏点创建围栏记录
                    for (FencePointDto point : fenceInfo.getPoints())
                    {
                        PackWarehouseFence fence = new PackWarehouseFence();
                        fence.setWarehouseId(packWarehouse.getWarehouseId());
                        fence.setFenceType(fenceInfo.getFenceType());

                        fence.setPointOrder(point.getPointOrder());
                        fence.setLatitude(point.getLatitude());
                        fence.setLongitude(point.getLongitude());
                        fence.setCreateBy(packWarehouse.getCreateBy());
                        fence.setCreateTime(DateUtils.getNowDate());
                        
                        packWarehouseFenceService.insertPackWarehouseFence(fence);
                        fenceIds.add(fence.getFenceId());
                    }
                }
            }
        }
        
        result.put("warehouseId", packWarehouse.getWarehouseId());
        result.put("warehouseCode", packWarehouse.getWarehouseCode());
        result.put("fenceIds", fenceIds);
        
        return result;
    }

    /**
     * 修改仓库（包含围栏操作）
     * 
     * @param packWarehouse 仓库
     * @return 结果信息，包含围栏操作结果列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> updatePackWarehouseWithFence(PackWarehouse packWarehouse)
    {
        Map<String, Object> result = new HashMap<>();
        List<FenceOperationResultDto> operationResults = new ArrayList<>();
        
        // 1. 更新仓库信息
        packWarehouse.setUpdateTime(DateUtils.getNowDate());
        int warehouseResult = packWarehouseMapper.updatePackWarehouse(packWarehouse);
        
        // 2. 处理围栏操作
        if (packWarehouse.getFenceOperations() != null && !packWarehouse.getFenceOperations().isEmpty())
        {
            for (FenceOperationDto operation : packWarehouse.getFenceOperations())
            {
                FenceOperationResultDto operationResult = new FenceOperationResultDto();
                operationResult.setOperationType(operation.getOperationType());
                
                try
                {
                    switch (operation.getOperationType())
                    {
                        case "create":
                            handleCreateFenceOperation(packWarehouse.getWarehouseId(), operation, operationResult, packWarehouse.getUpdateBy());
                            break;
                        case "update":
                            handleUpdateFenceOperation(operation, operationResult, packWarehouse.getUpdateBy());
                            break;
                        case "delete":
                            handleDeleteFenceOperation(operation, operationResult);
                            break;
                        default:
                            operationResult.setSuccess(false);
                            operationResult.setMessage("不支持的操作类型：" + operation.getOperationType());
                    }
                }
                catch (Exception e)
                {
                    operationResult.setSuccess(false);
                    operationResult.setMessage("操作失败：" + e.getMessage());
                }
                
                operationResults.add(operationResult);
            }
        }
        
        result.put("warehouseId", packWarehouse.getWarehouseId());
        result.put("fenceOperationResults", operationResults);
        
        return result;
    }

    /**
     * 删除仓库信息（包含围栏信息）
     * 
     * @param warehouseId 仓库主键
     * @param force 是否强制删除
     * @return 结果信息，包含删除的围栏信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> deletePackWarehouseWithFence(Long warehouseId, boolean force)
    {
        Map<String, Object> result = new HashMap<>();
        List<Long> deletedFenceIds = new ArrayList<>();
        
        // 1. 检查是否有器具在该仓库内（如果不是强制删除）
        if (!force)
        {
            // TODO: 检查仓库内是否有器具，这里需要根据实际的器具表来实现
            // 如果有器具存在，抛出异常
            // throw new ServiceException("仓库内存在器具，无法删除");
        }
        
        // 2. 查询并删除该仓库的所有围栏
        PackWarehouseFence queryFence = new PackWarehouseFence();
        queryFence.setWarehouseId(warehouseId);
        List<PackWarehouseFence> fenceList = packWarehouseFenceService.selectPackWarehouseFenceList(queryFence);
        
        for (PackWarehouseFence fence : fenceList)
        {
            packWarehouseFenceService.deletePackWarehouseFenceByFenceId(fence.getFenceId());
            deletedFenceIds.add(fence.getFenceId());
        }
        
        // 3. 删除仓库
        int warehouseResult = packWarehouseMapper.deletePackWarehouseByWarehouseId(warehouseId);
        
        result.put("warehouseId", warehouseId);
        result.put("deletedFenceIds", deletedFenceIds);
        result.put("deletedFenceCount", deletedFenceIds.size());
        
        return result;
    }

    /**
     * 处理新增围栏操作
     */
    private void handleCreateFenceOperation(Long warehouseId, FenceOperationDto operation, 
                                          FenceOperationResultDto operationResult, String createBy)
    {
        if (operation.getPoints() == null || operation.getPoints().size() < 3)
        {
            operationResult.setSuccess(false);
            operationResult.setMessage("围栏坐标点不足，至少需要3个点");
            return;
        }
        
        Long fenceId = null;
        for (FencePointDto point : operation.getPoints())
        {
            PackWarehouseFence fence = new PackWarehouseFence();
            fence.setWarehouseId(warehouseId);
            fence.setFenceType(operation.getFenceType());
            fence.setPointOrder(point.getPointOrder());
            fence.setLatitude(point.getLatitude());
            fence.setLongitude(point.getLongitude());
            fence.setCreateBy(createBy);
            fence.setCreateTime(DateUtils.getNowDate());
            
            packWarehouseFenceService.insertPackWarehouseFence(fence);
            if (fenceId == null) {
                fenceId = fence.getFenceId();
            }
        }
        
        operationResult.setSuccess(true);
        operationResult.setFenceId(fenceId);
        operationResult.setMessage("围栏新增成功");
    }

    /**
     * 处理修改围栏操作
     */
    private void handleUpdateFenceOperation(FenceOperationDto operation, 
                                          FenceOperationResultDto operationResult, String updateBy)
    {
        if (operation.getFenceId() == null)
        {
            operationResult.setSuccess(false);
            operationResult.setMessage("围栏ID不能为空");
            return;
        }
        
        // 先删除原有围栏点，再新增
        PackWarehouseFence existingFence = packWarehouseFenceService.selectPackWarehouseFenceByFenceId(operation.getFenceId());
        if (existingFence == null)
        {
            operationResult.setSuccess(false);
            operationResult.setMessage("围栏不存在");
            return;
        }
        
        // 删除同一仓库同一围栏类型的所有点
        PackWarehouseFence queryFence = new PackWarehouseFence();
        queryFence.setWarehouseId(existingFence.getWarehouseId());
        queryFence.setFenceType(existingFence.getFenceType());
        List<PackWarehouseFence> fenceList = packWarehouseFenceService.selectPackWarehouseFenceList(queryFence);
        
        for (PackWarehouseFence fence : fenceList)
        {
            packWarehouseFenceService.deletePackWarehouseFenceByFenceId(fence.getFenceId());
        }
        
        // 新增修改后的围栏点
        if (operation.getPoints() != null && operation.getPoints().size() >= 3)
        {
            for (FencePointDto point : operation.getPoints())
            {
                PackWarehouseFence fence = new PackWarehouseFence();
                fence.setWarehouseId(existingFence.getWarehouseId());
                fence.setFenceType(operation.getFenceType());
                fence.setPointOrder(point.getPointOrder());
                fence.setLatitude(point.getLatitude());
                fence.setLongitude(point.getLongitude());
                fence.setCreateBy(updateBy);
                fence.setCreateTime(DateUtils.getNowDate());
                
                packWarehouseFenceService.insertPackWarehouseFence(fence);
            }
        }
        
        operationResult.setSuccess(true);
        operationResult.setFenceId(operation.getFenceId());
        operationResult.setMessage("围栏修改成功");
    }

    /**
     * 处理删除围栏操作
     */
    private void handleDeleteFenceOperation(FenceOperationDto operation, FenceOperationResultDto operationResult)
    {
        if (operation.getFenceId() == null)
        {
            operationResult.setSuccess(false);
            operationResult.setMessage("围栏ID不能为空");
            return;
        }
        
        PackWarehouseFence existingFence = packWarehouseFenceService.selectPackWarehouseFenceByFenceId(operation.getFenceId());
        if (existingFence == null)
        {
            operationResult.setSuccess(false);
            operationResult.setMessage("围栏不存在");
            return;
        }
        
        // 删除同一仓库同一围栏类型的所有点
        PackWarehouseFence queryFence = new PackWarehouseFence();
        queryFence.setWarehouseId(existingFence.getWarehouseId());
        queryFence.setFenceType(existingFence.getFenceType());
        List<PackWarehouseFence> fenceList = packWarehouseFenceService.selectPackWarehouseFenceList(queryFence);
        
        for (PackWarehouseFence fence : fenceList)
        {
            packWarehouseFenceService.deletePackWarehouseFenceByFenceId(fence.getFenceId());
        }
        
        operationResult.setSuccess(true);
        operationResult.setFenceId(operation.getFenceId());
        operationResult.setMessage("围栏删除成功");
    }

    // 导入功能已移除，如需使用请取消注释
    /*
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importWarehouse(List<PackWarehouse> warehouseList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(warehouseList) || warehouseList.size() == 0) {
            throw new ServiceException("导入仓库数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (PackWarehouse warehouse : warehouseList) {
            try {
                // 验证是否存在这个仓库
                PackWarehouse existWarehouse = packWarehouseMapper.selectPackWarehouseByWarehouseCode(warehouse.getWarehouseCode());
                if (StringUtils.isNull(existWarehouse)) {
                    warehouse.setCreateBy(operName);
                    warehouse.setCreateTime(DateUtils.getNowDate());
                    warehouse.setStatus("1"); // 默认启用状态
                    this.insertPackWarehouse(warehouse);
                    successNum++;
                } else if (isUpdateSupport) {
                    warehouse.setWarehouseId(existWarehouse.getWarehouseId());
                    warehouse.setUpdateBy(operName);
                    warehouse.setUpdateTime(DateUtils.getNowDate());
                    this.updatePackWarehouse(warehouse);
                    successNum++;
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、仓库 " + warehouse.getWarehouseName() + " 导入失败：仓库编码已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、仓库 " + warehouse.getWarehouseName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "导入完成！成功 " + successNum + " 条，失败 " + failureNum + " 条，失败原因如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            return "恭喜您，数据已全部导入成功！共 " + successNum + " 条数据。";
        }
    }
    */
} 